import React, {useEffect, useState} from 'react';
import {View, Button, Text, TextInput} from 'react-native';
import {SimpleInfoContract} from '../contracts/SimpleInfo';
import {build_raw_tx} from '../utils/txhelper';
import '../utils/myglobal.js';
import mystyles from './mystyles';

import {bcos_raw, bcos_rpc} from '../utils/bcosproxy_util';
import {Exception} from '../utils/bcosutils';
import eventBus from '../utils/ContractEventBus';
const DemoSimpleInfo = () => {
  const [inputData, setInputData] = useState('100');
  const [balance, setBalance] = useState('NaN');
  const [resultData, setResultData] = useState('waiting click...');
  const dofetch = function (mode) {
    console.log('mode = ', mode);
    fetchData(mode);
  };
  let contract = new SimpleInfoContract();
  let contractname = 'SimpleInfo';
  let address = '0xa7d8d7d45b3b38dedc6c91716cba23e946ad3bf1';
  function doGetbalance(cmd) {
    let get_raw_data = contract.create_getbalance();
    bcos_raw('call', contractname, address, get_raw_data).then(result => {
      //console.log('get raw result  ', result);
      //let jsonResult = JSON.parse(result);
      if ('output_result' in result) {
        setBalance(result.output_result);
        if (cmd == 'getbalance') {
          setResultData('查询结果: [' + result.output_result + ']');
        }
      } else {
        console.error(result);
        setResultData('查询出错');
      }
    });
  }
  const fetchData = async cmd => {
    try {
      console.log('global url', global.proxy_url);
      console.log('fetchData mode:', cmd);

      let blocklimit = 0;

      if (cmd == 'add') {
        const blocklimitresponse = await bcos_rpc('getBlocklimit'); // 替换为你的URL
        /*rpc的错误有待处理，当网络错误时，会出现返回的是空所以，[RangeError: number is not integral]*/
        console.log(`blocklimitresponse ${blocklimitresponse}`);
        blocklimit = parseInt(blocklimitresponse);

        console.log('blocklimit ', blocklimit);
        let func_set = contract.create_add(inputData);
        let set_raw_data = build_raw_tx(blocklimit, address, func_set);
        bcos_raw('sendtx', contractname, address, set_raw_data).then(result => {
          if (result == undefined) {
            throw new Error('sendtx return undefined');
          }
          if ('status' in result) {
            setResultData(
              '发送交易: [ ' + inputData + ' ], 结果 : ' + result.status,
            );
            doGetbalance(cmd);
            //触发一个事件
            var eventName = 'tx';
            console.log('Event--> fire', eventName);
            eventBus.emit(eventName, {
              contract: contractname,
              address: address,
              function: 'add',
            });
          } else {
            console.error(result);
          }
        });
      } else if (cmd == 'getbalance') {
        let res = doGetbalance(cmd);
      }
    } catch (error) {
      console.error('doAdd error:', error);
      //console.stack(error)
      setResultData('操作失败: [ ' + error);
    }
  };

  useEffect(() => {
    doGetbalance('');
  }, []);

  return (
    <View style={{width: '100%', alignSelf: 'center'}}>
      <View style={{flexDirection: 'row'}}>
        <Text style={[mystyles.SubTitle, {paddingVertical: 1}]}>
          积分余额合约:
        </Text>
        <Text style={[mystyles.text, {fontSize: 14, color: 'darkblue'}]}>
          {address}
        </Text>
      </View>
      <Text style={mystyles.SubTitle}>当前余额: {balance}</Text>
      <View style={{flexDirection: 'row'}}>
        <Text style={[mystyles.text]}>输入充值额 : </Text>

        <TextInput
          id="userinput"
          style={{
            flex: 1,
            height: 40,
            borderColor: 'darkblue',
            borderWidth: 1,
          }}
          onChangeText={v => {
            setInputData(v);
            //console.log('inputData is ' + v);
          }}
          defaultValue={inputData}
        />
      </View>
      <Text style={[mystyles.text, {color: '#33a8ff'}]}>{resultData}</Text>
      <View>
        <Button title="查余额" onPress={() => fetchData('getbalance')} />
        <View style={mystyles.separator} />
        <Button title="充值" onPress={() => fetchData('add')} />
      </View>
    </View>
  );
};

export default DemoSimpleInfo;
